from flask import jsonify, request
from services.avatar_service import AvatarService
from services.auth_service import AuthService
import os

class AvatarController:
    """头像控制器类 - 处理头像上传相关请求"""
    
    def __init__(self):
        self.avatar_service = AvatarService()
        self.auth_service = AuthService()
    
    def upload_avatar(self):
        """上传用户头像"""
        try:
            # 从请求头获取token并验证
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            # 验证token并获取用户名
            payload = self.auth_service.verify_token(token)
            if not payload:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            username = payload.get('username')
            
            # 检查是否有文件上传
            if 'avatar' not in request.files:
                return jsonify({
                    'success': False,
                    'message': '没有上传文件'
                }), 400
            
            file = request.files['avatar']
            
            # 检查文件名
            if file.filename == '':
                return jsonify({
                    'success': False,
                    'message': '未选择文件'
                }), 400
            
            # 验证文件类型
            allowed_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
            filename = file.filename or ''
            file_extension = os.path.splitext(filename)[1].lower()
            
            if file_extension not in allowed_extensions:
                return jsonify({
                    'success': False,
                    'message': '不支持的文件格式，仅支持JPG、PNG、GIF、BMP、WebP格式'
                }), 400
            
            # 读取文件内容
            file_data = file.read()
            
            # 检查文件大小（限制为5MB）
            if len(file_data) > 5 * 1024 * 1024:
                return jsonify({
                    'success': False,
                    'message': '文件大小超过限制（最大5MB）'
                }), 400
            
            # 调用服务上传头像
            result = self.avatar_service.upload_avatar(username, file_data, file_extension)
            
            return jsonify(result), 200 if result['success'] else 400
            
        except Exception as e:
            print(f"上传头像控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '上传头像失败，服务器错误'
            }), 500
    
    def delete_avatar(self):
        """删除用户头像"""
        try:
            # 从请求头获取token并验证
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            # 验证token并获取用户名
            payload = self.auth_service.verify_token(token)
            if not payload:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            username = payload.get('username')
            
            # 调用服务删除头像
            result = self.avatar_service.delete_avatar(username)
            
            return jsonify(result), 200 if result['success'] else 400
            
        except Exception as e:
            print(f"删除头像控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '删除头像失败，服务器错误'
            }), 500